package com.spe.shangcheng.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spe.common.utils.PageUtils;
import com.spe.common.utils.Query;

import com.spe.shangcheng.product.dao.CategoryDao;
import com.spe.shangcheng.product.entity.CategoryEntity;
import com.spe.shangcheng.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntityAll = baseMapper.selectList(null);
        //找到一级分类
        List<CategoryEntity> categoryEntityListOne = categoryEntityAll.stream().filter(categoryEntity ->
            categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildren(menu,categoryEntityAll));
            return menu;
        }).sorted((menu1,menu2)-> (menu1.getSort()==null?0:menu1.getSort())-menu2.getSort()).toList();
        return categoryEntityListOne;
    }

    private List<CategoryEntity> getChildren(CategoryEntity categoryEntityParent,List<CategoryEntity>  categoryEntityAll){
        return categoryEntityAll.stream().filter(category -> category.getParentCid().equals(categoryEntityParent.getCatId()))
                .map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity,categoryEntityAll));
            return categoryEntity;
        }).sorted((menu1,menu2)-> (menu1.getSort()==null?0:menu1.getSort())-menu2.getSort()).toList();

    }
    @Override
    public void removeMenuByIds(List<Long> catIds){
        //todo 检查是否存在子菜单
        baseMapper.deleteByIds(catIds);
    }
}